package com.efounder.login;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.efounder.chat.model.Constant;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.model.CheckAppVersionUtilInterface;
import com.efounder.model.CheckRESUtilInterface;
import com.efounder.model.RESUpdateManager;
import com.efounder.model.RefreshViewEvent;
import com.efounder.ospmobilelib.R;
import com.efounder.util.AbAppUtil;
import com.efounder.util.AppContext;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.FileDeleteUtil;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ProgressDialogForUpdate;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.NewVersionAlertDialog;
import com.utilcode.util.AppUtils;
import com.utilcode.util.FileUtils;
import com.utilcode.util.LogUtils;
import com.zhuiji7.filedownloader.download.DownLoadListener;
import com.zhuiji7.filedownloader.download.DownLoadManager;
import com.zhuiji7.filedownloader.download.DownLoadService;
import com.zhuiji7.filedownloader.download.dbcontrol.FileHelper;
import com.zhuiji7.filedownloader.download.dbcontrol.bean.SQLDownLoadInfo;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static com.efounder.forwechat.BaseApp.context;
import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_ADDRESS;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PATH;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PORT;

/**
 * 使用restful登录检查应用版本号以及资源文件版本号相关
 * on 2016/8/25 0025.
 */

public class APKUpdateControl {

    private String TAG = "APKUpdateControl";
    private CheckAppVersionUtilInterface checkAppVersionUtilInterface;
    /**
     * 使用DownLoadManager时只能通过DownLoadService.getDownLoadManager()的方式来获取下载管理器，不能通过new DownLoadManager()的方式创建下载管理器
     */
    private DownLoadManager manager;
    private String apkDownUrl = "";
    private static float lastScale, nowScale;
    private static boolean isPaused = false;
    /**
     * 服务器返回的版本号
     */
    private String serverVersion;

    public APKUpdateControl() {
    }

    /**
     * 检查当前版本apk是否需要更新
     *
     * @param serverVersion 服务器返回的app版本号
     * @return 版本号是否一致
     */
    public boolean needUpdateApkByCompileVersion(String serverVersion) {
        this.serverVersion = serverVersion;
        Log.e(TAG, "服务器中APP版本为：" + serverVersion);

        AppUtils.AppInfo appInfo = AppUtils.getAppInfo();
        //如果本地版本比服务器版本高，则不升级，这是为了方便我们撤回发布的新版本
        if (appInfo.getVersionName().compareTo(serverVersion) > 0) {
            return false;
        }

        //清除当前版本下载的apk的文件夹
        String fileLocationDir = FileHelper.getBaseFilePath() + File.separator + appInfo.getVersionName();
        FileUtils.deleteDir(fileLocationDir);
//        FileHelper.DeleteFolder(fileLocation);
        //比对版本是否一致
        if (!serverVersion.equals(appInfo.getVersionName())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查是否需要强制升级
     * 规则：版本号第一第二位不同需强制升级
     *
     * @param serverVersion
     * @return
     */
    public static boolean checkIsNeedForceDown(String serverVersion) {

        AppUtils.AppInfo appInfo = AppUtils.getAppInfo();
        if (serverVersion.equals(appInfo.getVersionName())) {
            return false;
        }

        String[] serverVersions = serverVersion.split("\\.");
        String[] localVersions = appInfo.getVersionName().split("\\.");
        if (localVersions != null && localVersions.length == 3 && serverVersions != null && serverVersions.length == 3) {
            if (!serverVersions[0].equals(localVersions[0])) {//版本号第一位不相同，强制升级
                return true;
            }
            if (!serverVersions[1].equals(localVersions[1])) {//版本号第2位不相同，强制升级
                return true;
            }
        }
        return false;
    }

    /**
     * 初始化下载服务
     *
     * @param
     */
    public void startDownLoadFile(String _apkDownUrl, CheckAppVersionUtilInterface _checkAppVersionUtilInterface) {
        apkDownUrl = _apkDownUrl;
        checkAppVersionUtilInterface = _checkAppVersionUtilInterface;
        startDownLoad();
    }

    private void startDownLoad() {

        /*获取下载管理器*/
        manager = DownLoadService.getDownLoadManager();

        if (manager == null) {
            return;
        }

        /*设置用户ID，客户端切换用户时可以显示相应用户的下载任务*/
        PackageInfo pi = AbAppUtil.getPackageInfo(AppContext.getInstance());
        manager.changeUser(serverVersion);
        //FileHelper.setUserID(pi.versionName);
        /*断点续传需要服务器的支持，设置该项时要先确保服务器支持断点续传功能*/
        manager.setSupportBreakpoint(true);
        manager.setCurrentTask(Constant.ApkFileName);
        /*服务器一般会有个区分不同文件的唯一ID，用以处理文件重名的情况*/
        //info.setFileName(Constant.ApkFileName);
        //info.setTaskID(Constant.ApkFileName);

        //info.setOnDownloading(true);
        /*将任务添加到下载队列，下载器会自动开始下载*/
        int i = manager.addTask(Constant.ApkFileName, apkDownUrl, Constant.ApkFileName);


//        final Timer timerFresh = new Timer();
//        timerFresh.schedule(new TimerTask() {
//            public void run() {
//                if (lastScale == nowScale && !isPaused && nowScale != 0) {
//                    downErrorHandler.sendEmptyMessage(0);
//                    //  Toast.makeText(context, "网络不稳定，请稍后再试，或者点击进度条双击右边按钮", 200).show();
//                }
//                nowScale = lastScale;
//                if ((int) (lastScale * 100) == 100)
//                    timerFresh.cancel();
//            }
//        }, 1000, 10000);

        final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(false).build());
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (lastScale == nowScale && !isPaused && nowScale != 0) {
                    downErrorHandler.sendEmptyMessage(0);
                    //  Toast.makeText(context, "网络不稳定，请稍后再试，或者点击进度条双击右边按钮", 200).show();
                }
                nowScale = lastScale;
                if ((int) (lastScale * 100) == 100) {
                    executorService.shutdown();
                }
            }
        }, 1000, 10000, TimeUnit.MILLISECONDS);


        manager.setSingleTaskListener(Constant.ApkFileName, new DownLoadListener() {
            @Override
            public void onStart(SQLDownLoadInfo sqlDownLoadInfo) {
            }

            @Override
            public void onProgress(SQLDownLoadInfo sqlDownLoadInfo, boolean isSupportBreakpoint) {
                //info.setDownFileSize(sqlDownLoadInfo.getDownloadSize());
                //info.setFileSize(sqlDownLoadInfo.getFileSize());

                float lastScale = (float) sqlDownLoadInfo.getDownloadSize() / sqlDownLoadInfo.getFileSize();
                Message message = new Message();
                message.arg1 = (int) (lastScale * 100);
                downProgressHandler.sendMessage(message);//发送message信息

            }

            @Override
            public void onStop(SQLDownLoadInfo sqlDownLoadInfo, boolean isSupportBreakpoint) {
                checkAppVersionUtilInterface.stop();
            }

            @Override
            public void onError(SQLDownLoadInfo sqlDownLoadInfo) {
                //如果出现其他类型的异常，会删除这条任务及cache文件，并重新启动任务,增加延时重新请求数据的功能。
                try {
                    Thread.sleep(3000);
                    manager.deleteTask(Constant.ApkFileName);
                    manager.addTask(Constant.ApkFileName, apkDownUrl, Constant.ApkFileName);
                    //info.setOnDownloading(true);
                    manager.setSingleTaskListener(Constant.ApkFileName, this);
                    manager.startTask(manager.getCurrentTask());
                } catch (Exception e) {
                }
                checkAppVersionUtilInterface.error();
            }

            @Override
            public void onSuccess(SQLDownLoadInfo sqlDownLoadInfo) {
                AppContext.getInstance().stopService(new Intent(AppContext.getInstance(), DownLoadService.class));
                final String TEMP_FILEPATH = FileHelper.getFileDefaultPath();
                String filePath = TEMP_FILEPATH + "/(" + FileHelper.filterIDChars(sqlDownLoadInfo.getFileName()) + ")" + sqlDownLoadInfo.getFileName();
                checkAppVersionUtilInterface.downloadOver(filePath);
            }

            @Override
            public void onNetError(SQLDownLoadInfo sqlDownLoadInfo) {
                try {
                    Thread.sleep(3000);
                    manager.startTask(manager.getCurrentTask());
                } catch (Exception e) {

                }
            }
        });
        //如果已经下载完毕
        if (i == -1) {
            final String TEMP_FILEPATH = FileHelper.getFileDefaultPath();
            String filePath = TEMP_FILEPATH + "/(" + FileHelper.filterIDChars(Constant.ApkFileName) + ")" + Constant.ApkFileName;
            checkAppVersionUtilInterface.downloadOver(filePath);
        } else {
            //info.setOnDownloading(true);
            manager.startTask(Constant.ApkFileName);
        }
    }

    public void stopDownApkTask() {
        if (manager != null) {
            manager.stopTask(Constant.ApkFileName);
        }
        isPaused = true;
        AppContext.getInstance().stopService(new Intent(AppContext.getInstance(), DownLoadService.class));

    }

    private Handler downErrorHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Toast.makeText(context, R.string.common_text_network_error, Toast.LENGTH_SHORT).show();
        }
    };
    private Handler downProgressHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            checkAppVersionUtilInterface.updateProgress(msg.arg1);
        }
    };


    /**
     * 检查是否需要升级apk，如果需要弹框升级，由弹框控制是否在下载
     *
     * @param mContext
     * @param response            服务器返回的版本信息
     * @param checkVersionHandler 响应 更新xml资源 更新界面操作
     * @return
     */
    public boolean CheckAPKVerion(Context mContext, String response, Handler checkVersionHandler) {
        LoadingDataUtilBlack.dismiss();

        boolean isNeedUpdateApk = false;
        if (TextUtils.isEmpty(response)) {
            //直接检查资源文件版本
            CheckRESVerion(mContext, response, checkVersionHandler);
            return false;
        }

        JSONObject jsonObject = JSON.parseObject(response);
        String appUpgrade = jsonObject.getString("appUpgrade");
        JSONObject appUpgradejsonObject = JSON.parseObject(appUpgrade);

        String androidInfo = appUpgradejsonObject.getString("android");
        if (TextUtils.isEmpty(androidInfo)) {
            //检查资源文件更新
            CheckRESVerion(mContext, response, checkVersionHandler);
        } else {
            JSONObject androidInfojsonObject = JSON.parseObject(androidInfo);
            String appFile = androidInfojsonObject.getString("appFile");
            if (null == appFile || appFile.equals("")) {
                return false;
            } else {
                JSONObject appFilejsonObject = JSON.parseObject(appFile);
                //升级说明
                String des = appFilejsonObject.getString("des");
                //下载链接
                apkDownUrl = appFilejsonObject.getString("path");
                //版本号
                String serverVersion = appFilejsonObject.getString("version");

                isNeedUpdateApk = needUpdateApkByCompileVersion(serverVersion) && !EnvSupportManager.isSupportGooglePlayUpgrade();
                boolean isForceUpdateApk = checkIsNeedForceDown(serverVersion);//是否需要强制升级
                if (isNeedUpdateApk) {

                    //默认是0 就是黑色的下载框
                    String appDownUIMode = EnvironmentVariable.getProperty("appDownUIVersion", "0");
                    if ("0".equals(appDownUIMode)) {
                        //https://fssc.cnpc.com.cn/BSServer/resources/androidYS/updateAndroidForWeChat.zip
                        downAPKByDefaultMode(mContext, response, des, apkDownUrl, isForceUpdateApk, checkVersionHandler);
                    } else {
                        downAPKByNewMode(mContext, response, des, apkDownUrl, isForceUpdateApk, checkVersionHandler);
                    }
                } else {

                    CheckRESVerion(mContext, response, checkVersionHandler);
                }
            }
        }

        return isNeedUpdateApk;
    }

    /**
     * APP下载
     *
     * @param appUpdateNote 更新说明
     * @param apkDownUrl    下载路径
     * @param isForceUpdate 是否强制升级
     */
    public void downAPKByDefaultMode(final Context mContext, final String response, String appUpdateNote, final String apkDownUrl, final boolean isForceUpdate, final Handler checkVersionHandler) {
        String note = "";
        if (appUpdateNote != null) {
            note = appUpdateNote.replace(";", "\n");
        }
        String dialogTitle = mContext.getResources().getString(R.string.common_text_app_update);
        if (!TextUtils.isEmpty(serverVersion)) {
            note = serverVersion + "\n" + note;
        }

        final ProgressDialogForUpdate progressDialogForUpdate = new ProgressDialogForUpdate(mContext, note, dialogTitle, mContext.getResources().getString(R.string.common_text_download_now), mContext.getResources().getString(R.string.common_text_cancel));

        progressDialogForUpdate.showDialog();
        if (isForceUpdate) {
            progressDialogForUpdate.getDialogBuild().getNegativeButton().setVisibility(View.GONE);
            progressDialogForUpdate.getDialogBuild().getNegativeButton().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ToastUtil.showToast(mContext, R.string.apk_update_control_tip_force_update);
                }
            });
            progressDialogForUpdate.getDialogBuild().getDialog().setCancelable(false);
            progressDialogForUpdate.getDialogBuild().getDialog().setCanceledOnTouchOutside(false);
        }
        progressDialogForUpdate.setOnDiaLogListener(new ProgressDialogForUpdate.OnDialogListener() {
            @Override
            public void dialogPositiveListener(DialogInterface dialogInterface, int which) {
                progressDialogForUpdate.getPositiveView().setClickable(false);
                progressDialogForUpdate.getPositiveView().setTextColor(Color.parseColor("#A5A5A5"));
                startDownLoadFile(apkDownUrl, new CheckAppVersionUtilInterface() {
                    @Override
                    public void startDown(float DownBeginFromPercent) {
                        //由于是由dialog控制是否在下载，而不是由下载控制dialog，所以这个方法是空的。
                    }

                    @Override
                    public void updateProgress(float progress) {
                        progressDialogForUpdate.updateProgress((int) progress);
                    }

                    @Override
                    public void downloadOver(String filePath) {
                        progressDialogForUpdate.dismiss();
//                        Intent install = new Intent();
//                        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        install.setAction(Intent.ACTION_VIEW);
//                        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                        File downloadFile = new File(filePath);
//                        install.setDataAndType(UriUtils.getUriForFile(downloadFile), "application/vnd.android.package-archive");
//                        mContext.startActivity(install);
                        //安装apk
                        AppUtils.installApp(filePath);

                    }

                    @Override
                    public void error() {
                        //下载出错
                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_network_error);
                    }

                    @Override
                    public void stop() {
                    }
                });
            }

            @Override
            public void dialogNegativeListener(DialogInterface dialogInterface, int which) {
                stopDownApkTask();
                progressDialogForUpdate.dismiss();
                if (response != null) {
                    CheckRESVerion(mContext, response, checkVersionHandler);
                }
            }

            @Override
            public void dialogCancelListener() {
                stopDownApkTask();
                progressDialogForUpdate.dismiss();
                if (response != null) {
                    CheckRESVerion(mContext, response, checkVersionHandler);
                }
            }
        });
    }

    /**
     * APP下载
     *
     * @param appUpdateNote 更新说明
     * @param apkDownUrl    下载路径
     * @param isForceUpdate 是否强制升级
     */
    public void downAPKByNewMode(final Context mContext, final String response, String appUpdateNote, final String apkDownUrl, final boolean isForceUpdate, final Handler mHandler) {
        String note = "";
        if (appUpdateNote != null) {
            note = appUpdateNote.replace(";", "\n");
        }
        final NewVersionAlertDialog newVersionAlertDialog = new NewVersionAlertDialog((Activity) mContext);
        newVersionAlertDialog.setTitle(mContext.getResources().getString(R.string.common_text_app_update));
        newVersionAlertDialog.setTextInfo(note);
        //设置中途不可暂停
        newVersionAlertDialog.setCanPause(false);
        newVersionAlertDialog.show();
        newVersionAlertDialog.setCanCancle(!isForceUpdate);

        newVersionAlertDialog.setListener(new NewVersionAlertDialog.UploadListener() {
            @Override
            public void onBegin() {
                beginDownLoadApk(newVersionAlertDialog, mContext, apkDownUrl);
            }

            @Override
            public void onPause() {

            }

            @Override
            public void onCancle() {
                stopDownApkTask();
                newVersionAlertDialog.dismiss();
                if (response != null) {
                    CheckRESVerion(mContext, response, mHandler);
                }
            }

            @Override
            public void onResume() {

            }
        });
    }

    private void beginDownLoadApk(final NewVersionAlertDialog dialog, final Context context, String apkDownUrl) {
        startDownLoadFile(apkDownUrl, new CheckAppVersionUtilInterface() {
            @Override
            public void startDown(float DownBeginFromPercent) {
                //由于是由dialog控制是否在下载，而不是由下载控制dialog，所以这个方法是空的。
            }

            @Override
            public void updateProgress(float progress) {
                dialog.setProgress(progress);
            }

            @Override
            public void downloadOver(String filePath) {
                dialog.dismiss();
                AppUtils.installApp(filePath);
            }

            @Override
            public void error() {
                Toast.makeText(context, R.string.common_text_error_retry, Toast.LENGTH_LONG).show();
            }

            @Override
            public void stop() {

            }
        });
    }

    /**
     * 第三部 判断是否需要升级资源文件
     *
     * @param response
     * @return
     */
    public boolean CheckRESVerion(Context context, String response, final Handler checkUpdateHandler) {

        //todo 某些应用资源文件集成在应用中,无需通过服务器检查资源文件更新
        if (EnvironmentVariable.getProperty("needCheckResVersion", "true").equals("false")) {
            //无需从服务器下载，那么我们判断是否需要更新assets下的资源文件
            if (LocalResUpdateManger.checkNeedUpdate()) {
                LocalResUpdateManger.updateLocalRes(new LocalResUpdateManger.ResUpdateCallback() {
                    @Override
                    public void updateFinish(boolean isSuccess) {
                        if (checkUpdateHandler != null && isSuccess) {
                            checkUpdateHandler.sendEmptyMessage(2);
                        }
                    }
                });
            } else {
                if (checkUpdateHandler != null) {
                    checkUpdateHandler.sendEmptyMessage(2);
                }
            }
            return false;
        }

        if (TextUtils.isEmpty(response)) {
            return false;
        }

        boolean isNeedUpdateRes = false;
        JSONObject jsonObject = JSON.parseObject(response);
        String appUpgrade = jsonObject.getString("appUpgrade");
        JSONObject appUpgradejsonObject = JSON.parseObject(appUpgrade);

        String androidInfo = appUpgradejsonObject.getString("android");
        if (null == androidInfo || androidInfo.equals("")) {
            return false;
        } else {
            JSONObject androidInfojsonObject = JSON.parseObject(androidInfo);
            String appResource = androidInfojsonObject.getString("appResource");
            if (null == appResource || appResource.equals("")) {
                return false;
            } else {
                JSONObject appResourcejsonObject = JSON.parseObject(appResource);

                String des = appResourcejsonObject.getString("des");
                String path = appResourcejsonObject.getString("path");
                String version = appResourcejsonObject.getString("version");


                final RESUpdateManager resUpdateManager = new RESUpdateManager();
                isNeedUpdateRes = resUpdateManager.checkIsNeedToDown(version);
                if (isNeedUpdateRes) {
                    //默认是0 就是黑色的下载框
                    String appDownUIMode = EnvironmentVariable.getProperty("appDownUIVersion", "0");
                    if ("0".equals(appDownUIMode)) {
                        downAPPResByDefaultMode(context, path, des, resUpdateManager, checkUpdateHandler);
                    } else {
                        downAPPResByNewMode(context, path, des, resUpdateManager, checkUpdateHandler);
                    }
                } else {
                    if (checkUpdateHandler != null) {//登陆界面 更新UI跳转
                        checkUpdateHandler.sendEmptyMessage(2);
                    }
                }
            }
        }
        return isNeedUpdateRes;

    }


    /**
     * 下载APP资源文件
     *
     * @param resUpdateNote
     * @param resUpdateManager
     */

    public void downAPPResByNewMode(final Context mContext, final String downUrl, String resUpdateNote,
                                    final RESUpdateManager resUpdateManager, final Handler mHandler) {
        String note = "";
        if (resUpdateNote != null) {
            note = resUpdateNote.replace(";", "\n");
        }

        final NewVersionAlertDialog newVersionAlertDialog = new NewVersionAlertDialog((Activity) mContext);
        newVersionAlertDialog.setTitle(mContext.getResources().getString(R.string.apk_update_control_update_source));
        newVersionAlertDialog.setTextInfo(note);
        newVersionAlertDialog.setCanCancle(true);
        newVersionAlertDialog.setCanPause(false);
        newVersionAlertDialog.show();
        newVersionAlertDialog.setListener(new NewVersionAlertDialog.UploadListener() {
            @Override
            public void onBegin() {
                String downurl1 = downUrl;
                if (downurl1 == null || "".equals(downurl1)) {
                    downurl1 = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE) + "://" + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS) + ":"
                            + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT) + "/"
                            + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PATH) + "/MobileResource/" + EnvironmentVariable.getProperty(KEY_SETTING_APPID)
                            + "/updateAndroidForWeChat.zip";
                }
                beginDownLoadRes(resUpdateManager, downurl1, mContext, newVersionAlertDialog, mHandler);
            }

            @Override
            public void onPause() {

            }

            @Override
            public void onCancle() {
                newVersionAlertDialog.dismiss();
                resUpdateManager.stopTask();
                String path = Constant.appSdcardLocation;
                File ESPMobileForWeChat = new File(path);
                //如果没有基本的配置文件
                boolean isNeedUpdateRES = ESPMobileForWeChat.exists();
                if (!isNeedUpdateRES) {
                    Toast.makeText(mContext, R.string.apk_update_control_tip_update_source, Toast.LENGTH_LONG).show();
                } else {
                    if (mHandler != null) {
                        mHandler.sendEmptyMessage(2);
                    }
                }
            }

            @Override
            public void onResume() {

            }
        });
    }


    private void beginDownLoadRes(final RESUpdateManager resUpdateManager, String downUrl, final Context context, final NewVersionAlertDialog newVersionAlertDialog, final Handler checkVersionHandler) {
        resUpdateManager.start(downUrl, new CheckRESUtilInterface() {
            @Override
            public void startDown(float DownBeginFromPercent) {
            }

            @Override
            public void updateProgress(float progress) {
                newVersionAlertDialog.setProgress(progress);
            }

            @Override
            public void downloadOver(String filePath) {
                newVersionAlertDialog.dismiss();
                //删除rn的文件夹 yqs
                FileDeleteUtil.DeleteFolder(Constant.UNZIP_DIR + "/reactnative");
                LoadingDataUtilBlack.show(context, context.getResources().getString(R.string.common_text_isunziping));
                resUpdateManager.unzipAndEncryptFile(filePath);
            }

            @Override
            public void error() {
                Toast.makeText(context, R.string.apk_update_control_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void stop() {
                //Toast.makeText(context, "网络异常，请稍后重试", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void unZIPOVER(String versionFromServer) {
                //设置新的资源文件版本号
                context.getSharedPreferences("res_version",
                        Context.MODE_PRIVATE).edit()
                        .putString("res_version", versionFromServer)
                        .commit();
                Message message = new Message();
                message.what = 1;
                checkVersionHandler.sendMessage(message);
                //新增eventbus 通知刷新
                EventBus.getDefault().post(new RefreshViewEvent(RefreshViewEvent.VIEW_TABOTTOMACTIVITY));
//                LoadingDataUtilBlack.dismiss();
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        LoadingDataUtilBlack.dismiss();
                    }
                });
                // CheckIM(ro);
            }
        });
    }

    public void downAPPResByDefaultMode(final Context mContext, final String downUrl, String resUpdateNote, final RESUpdateManager resUpdateManager, final Handler checkVersionHandler) {
        String note = "";
        if (resUpdateNote != null) {
            note = resUpdateNote.replace(";", "\n");
        }
        final ProgressDialogForUpdate progressDialogForUpdate = new ProgressDialogForUpdate(mContext, note, mContext.getResources().getString(R.string.apk_update_control_update_source), mContext.getResources().getString(R.string.common_text_download_now),
                mContext.getResources().getString(R.string.common_text_cancel));
        progressDialogForUpdate.showDialog();
        progressDialogForUpdate.setOnDiaLogListener(new ProgressDialogForUpdate.OnDialogListener() {
            @Override
            public void dialogPositiveListener(DialogInterface dialogInterface, int which) {
                progressDialogForUpdate.getPositiveView().setClickable(false);
                progressDialogForUpdate.getPositiveView().setTextColor(Color.parseColor("#A5A5A5"));
                resUpdateManager.start(downUrl, new CheckRESUtilInterface() {
                    @Override
                    public void startDown(float DownBeginFromPercent) {
                    }

                    @Override
                    public void updateProgress(float progress) {
                        progressDialogForUpdate.updateProgress((int) progress);
                    }

                    @Override
                    public void downloadOver(String filePath) {
                        progressDialogForUpdate.dismiss();
                        LoadingDataUtilBlack.show(mContext, ResStringUtil.getString(R.string.common_text_isunziping));
                        resUpdateManager.unzipAndEncryptFile(filePath);
                    }

                    @Override
                    public void error() {
                        Toast.makeText(mContext, R.string.apk_update_control_error, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void stop() {
                    }

                    @Override
                    public void unZIPOVER(String versionFromServer) {
                        //设置新的资源文件版本号
                        mContext.getSharedPreferences("res_version",
                                Context.MODE_PRIVATE).edit()
                                .putString("res_version", versionFromServer)
                                .commit();
                        Message message = new Message();
                        message.what = 1;
                        checkVersionHandler.sendMessage(message);
                        //新增eventbus 通知刷新
                        EventBus.getDefault().post(new RefreshViewEvent(RefreshViewEvent.VIEW_TABOTTOMACTIVITY));

                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                LoadingDataUtilBlack.dismiss();
                            }
                        });
                    }
                });
            }

            @Override
            public void dialogNegativeListener(DialogInterface dialogInterface, int which) {
                progressDialogForUpdate.dismiss();
                resUpdateManager.stopTask();
                String path = Constant.appSdcardLocation;
                File ESPMobileForWeChat = new File(path);
                //如果没有基本的配置文件
                boolean isNeedUpdateRES = ESPMobileForWeChat.exists();
                if (!isNeedUpdateRES) {
                    Toast.makeText(mContext, R.string.apk_update_control_tip_update_source, Toast.LENGTH_LONG).show();
                } else {
                    if (checkVersionHandler != null) {
                        checkVersionHandler.sendEmptyMessage(2);
                    }
                }
            }

            @Override
            public void dialogCancelListener() {
                resUpdateManager.stopTask();
                progressDialogForUpdate.dismiss();
            }
        });
    }
}



